<template>
	<div class="main-wrapper">
		<div class="search-wrapper">
			<span>实验名称：</span>
			<el-input placeholder="请输入实验名称" v-model="name" style="width: 200px;" clearable>
			</el-input>
			<span class="search_label">所属专业：</span>
			<el-select v-model="majorId" placeholder="请选择专业" style="width:200px" clearable>
				<el-option v-for="item in majors" :key="item.id" :label="item.name" :value="item.id">
				</el-option>
			</el-select>
			<!--<span class="search_label">实验模式：</span>
			<el-select v-model="mode" placeholder="请选择实验模式" style="width:200px" clearable>
				<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
				</el-option>
			</el-select>-->
			<el-button type="primary" @click="currentChange(1)" style="margin-left: 5px">搜索</el-button>
			<el-button type="primary" @click="openAdd()">添加实验</el-button>
			<!--<el-button @click="toJurisdiction" type="success">组织权限</el-button>-->
			<!--<el-button type="primary" @click="regettaskList">考核管理</el-button>-->
		</div>
		<div class="page-wrapper">
			<el-table :data="treeData" border>
				<div slot="empty" v-show='treeData'>
					<span style="color: #1482F0;font-size: 16px;">
						<i class="iconfont iconwushuju" style="font-size: 22px;"></i>&nbsp;&nbsp;暂无数据
					</span>
				</div>
				<el-table-column prop="cover" label="封面" width="140px" align='center'>
					<template slot-scope="scope">
						<el-image :src="baseurl+scope.row.cover" class="cover-content" fit="cover">
							<div slot="error" class="image-slot">
								<i class="el-icon-picture-outline"></i>
							</div>
						</el-image>
					</template>
				</el-table-column>
				<el-table-column prop="name" label="实验名称" show-overflow-tooltip align='center'>
					<template slot-scope="scope">
						<span @click="openInfo(scope.row)" class="link_index">{{scope.row.name}}</span>
					</template>
				</el-table-column>
				<el-table-column prop="majorName" label="专业" align='center' />
				<el-table-column prop="updateTime" label="更新时间" align='center' />
				<el-table-column prop="modeDtoList" label="实验模式" align='center'>
					<template slot-scope="scope">
						<span v-if="!scope.row.modeDtoList || scope.row.modeDtoList.length == 0">-</span>
						<el-tag v-for="item in scope.row.modeDtoList" :type='item.mode=="1"?"info":""' style='margin: 0 5px;'>{{item.mode=="1"?"学习":"考核"}}</el-tag>
					</template>
				</el-table-column>
				<!--<el-table-column prop="pictureQualityDtoList" label="实验画质" width='240' align='center'>
					<template slot-scope="scope">
						<span v-if="!scope.row.pictureQualityDtoList || scope.row.pictureQualityDtoList.length == 0">-</span>
						<el-tag type='success' v-for="item in scope.row.pictureQualityDtoList" style='margin: 0 5px;'>
							{{item.pictureQuality=="1"?"低画质":""}} {{item.pictureQuality=="2"?"中画质":""}} {{item.pictureQuality=="3"?"高画质":""}}
						</el-tag>
					</template>
				</el-table-column>-->
				<el-table-column prop="majorId" label="操作" width='360' align='center'>
					<template slot-scope="scope">
						<el-button type='primary' size='small' @click="openResource(scope.row)">模式管理</el-button>
						<!--<el-button type='success' size='small' @click="openDetail(scope.row)">资源管理</el-button>-->
						<el-button type='primary' size='small' @click="openEdit(scope.row)">编辑</el-button>
						<el-button type="danger" size='small' @click="openDelete(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div style="width: 100%;margin: 15px;text-align: center;">
				<el-pagination @current-change="currentChange" :current-page="current" :page-size="limit" layout="total,  prev, pager, next, jumper" :total="total"></el-pagination>
			</div>
		</div>
		<el-dialog title="创建实验" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' width='720px' destroy-on-close :visible.sync="addStatus" class='paddingSmall coursedialog'>
			<el-form :model="form" :rules="rules" ref='addForm'>
				<el-form-item label="实验名称" :label-width="formLabelWidth" prop="name">
					<el-col :span="24">
						<el-input v-model="form.name" autocomplete="off" placeholder="请输入实验名称" style="width: 100%;"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="实验分类" :label-width="formLabelWidth" prop="majorId">
					<el-col :span="24">
						<el-select v-model="form.majorId" placeholder="请选择专业" style="width:100%" clearable>
							<el-option v-for="item in majors" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-col>
				</el-form-item>
				<!--<el-form-item label="及格分" :label-width="formLabelWidth" prop="passScore">
					<el-col :span="24">
						<el-input v-model="form.passScore" placeholder="请输入及格分" autocomplete="off"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="考试限时" :label-width="formLabelWidth" prop="timeLimit">
					<el-col :span="24">
						<el-input v-model="form.timeLimit" placeholder="请输入考试限时(秒)" autocomplete="off"></el-input>
					</el-col>
				</el-form-item>-->
				<el-form-item label="实验描述" :label-width="formLabelWidth" prop="describes">
					<el-col :span="24">
						<el-input v-model="form.describes" resize='none' type="textarea" :autosize="{ minRows: 2, maxRows: 2}" placeholder="请输入实验描述" autocomplete="off">
						</el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="实验介绍" :label-width="formLabelWidth" prop="introduction">
					<el-col :span="24">
						<editor-more :content='form.introduction' @change='introductionAddChange'></editor-more>
					</el-col>
				</el-form-item>
				<el-form-item label="封面" :label-width="formLabelWidth" prop="cover">
					<el-col :span="24">
						<el-upload action="" list-type="picture-card" :multiple='false' :with-credentials='true' accept='.jpg,.jpeg,.png' name='file' :on-success='formBannerSuccess' :on-remove='formBannerRemove' :file-list="form.coverFiles" :http-request="formRequest">
							<i class="el-icon-plus"></i>
						</el-upload>
					</el-col>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeAdd">取 消</el-button>
				<el-button type="primary" @click="add()" :disabled='dataloading'>保 存</el-button>
			</div>
		</el-dialog>
		<el-dialog title="编辑实验" width='720px' destroy-on-close :visible.sync="editStatus" class='paddingSmall coursedialog' :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true'>
			<el-form :model="formEdit" :rules="rules" ref='editForm'>
				<el-form-item label="实验名称" :label-width="formLabelWidth" prop="name">
					<el-col :span="24">
						<el-input v-model="formEdit.name" autocomplete="off" placeholder="请选择实验名称" style="width: 100%;"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="实验分类" :label-width="formLabelWidth" prop="majorId">
					<el-col :span="24">
						<el-select v-model="formEdit.majorId" placeholder="请选择专业" style="width:100%" clearable>
							<el-option v-for="item in majors" :key="item.id" :label="item.name" :value="item.id">
							</el-option>
						</el-select>
					</el-col>
				</el-form-item>
				<!--<el-form-item label="及格分" :label-width="formLabelWidth" prop="passScore">
					<el-col :span="24">
						<el-input v-model="formEdit.passScore" placeholder="请输入及格分" autocomplete="off"></el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="考试限时" :label-width="formLabelWidth" prop="timeLimit">
					<el-col :span="24">
						<el-input v-model="formEdit.timeLimit" placeholder="请输入考试限时(秒)" autocomplete="off"></el-input>
					</el-col>
				</el-form-item>-->
				<el-form-item label="实验描述" :label-width="formLabelWidth" prop="describes">
					<el-col :span="24">
						<el-input v-model="formEdit.describes" resize='none' type="textarea" :autosize="{ minRows: 2, maxRows: 2}" placeholder="请输入实验描述" autocomplete="off">
						</el-input>
					</el-col>
				</el-form-item>
				<el-form-item label="实验介绍" :label-width="formLabelWidth" prop="introduction">
					<el-col :span="24">
						<editor-more :content='formEdit.introduction' @change='introductionEditChange'></editor-more>
					</el-col>
				</el-form-item>
				<el-form-item label="封面" :label-width="formLabelWidth" prop="cover">
					<el-col :span="24">
						<el-upload action="" list-type="picture-card" :multiple='false' :with-credentials='true' accept='.jpg,.jpeg,.png' name='file' :on-success='formEditBannerSuccess' :on-remove='formEditBannerRemove' :file-list="formEdit.coverFiles" :http-request="formRequest">
							<i class="el-icon-plus"></i>
						</el-upload>
					</el-col>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="closeEdit">取 消</el-button>
				<el-button type="primary" @click="edit()" :disabled='dataloading'>保 存</el-button>
			</div>
		</el-dialog>
		<el-dialog title="考核管理" width="65%" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' :visible.sync="tableshow" class='workDialog'>
			<div style="height: 34px;font-size: 16px;font-weight: bold;">当前选择实验数：{{selections.length}}</div>
			<div style="margin-bottom: 10px">
				<span class="topic-courselabel">实验名称：</span>
				<el-input prefix-icon="el-icon-search" width="30px" v-model="searchName" placeholder="请输入题干名称" style="width:200px;height:36px;" clearable>
				</el-input>
				<span class="topic-courselabel">实验分类：</span>
				<el-cascader @change='handleExamChange(1)' v-model="searchType" :options="majors" :props='props' placeholder="请选择实验分类" style="width:200px;height:36px;" clearable></el-cascader>
				<span class="search_label">实验模式：</span>
				<el-select v-model="searchMode" placeholder="请选择实验模式" style="width:200px" clearable>
					<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
					</el-option>
				</el-select>
				<el-button type="primary" @click="handleExamChange(1)" style="margin-left: 5px">搜索</el-button>
			</div>
			<el-table :data="taskList" border style="width: 100%" @selection-change="selectionChange" row-key="vrResourceDetailId" ref='taskList'>
				<el-table-column align='center' type="selection" :reserve-selection='true'>
				</el-table-column>
				<el-table-column prop="cover" label="封面" width="140px" align='center'>
					<template slot-scope="scope">
						<el-image :src="baseurl+scope.row.cover" class="cover-content" fit="cover">
							<div slot="error" class="image-slot">
								<i class="el-icon-picture-outline"></i>
							</div>
						</el-image>
					</template>
				</el-table-column>
				<el-table-column prop="name" label="实验名称" show-overflow-tooltip align='center' />
				<el-table-column prop="majorName" label="专业" align='center' />
				<el-table-column prop="updateTime" label="更新时间" align='center' />
				<el-table-column prop="modeDtoList" label="实验模式" align='center'>
					<template slot-scope="scope">
						<span v-if="!scope.row.modeDtoList || scope.row.modeDtoList.length == 0">-</span>
						<el-tag v-for="item in scope.row.modeDtoList" :type='item.mode=="1"?"info":""' style='margin: 0 5px;'>{{item.mode=="1"?"学习":"考核"}}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="pictureQualityDtoList" label="实验画质" width='240' align='center'>
					<template slot-scope="scope">
						<span v-if="!scope.row.pictureQualityDtoList || scope.row.pictureQualityDtoList.length == 0">-</span>
						<el-tag type='success' v-for="item in scope.row.pictureQualityDtoList" style='margin: 0 5px;'>
							{{item.pictureQuality=="1"?"低画质":""}} {{item.pictureQuality=="2"?"中画质":""}} {{item.pictureQuality=="3"?"高画质":""}}
						</el-tag>
					</template>
				</el-table-column>
			</el-table>
			<div style="margin: 15px 0;text-align: center;">
				<el-pagination background @current-change="handleExamChange" :current-page="examCurrent" :page-size="examLimit" layout="total, prev, pager, next, jumper" :total="examTotal">
				</el-pagination>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="calcelSelection">取 消</el-button>
				<el-button type="success" @click="addSelection(1)" :disabled="!selections || selections.length<=0">全部开启</el-button>
				<el-button type="danger" @click="addSelection(0)" :disabled="!selections || selections.length<=0">全部关闭</el-button>
			</div>
		</el-dialog>
		<el-dialog title="模式管理" width="600px" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' :visible.sync="resourceshow" class='workDialog'>
			<el-button type='primary' size='small' @click="openAddMode()" style='margin: 0 0 15px 0;'>添加</el-button>
			<el-table :data="modeDtoList" border>
				<el-table-column prop="name" label="实验模式" align='center'>
					<template slot-scope="scope">
						{{scope.row.mode=="1"?"学习":"考核"}}
					</template>
				</el-table-column>
				<el-table-column prop="version" label="实验版本" align='center'>
					<template slot-scope="scope">
						<span v-for="item in versions" v-if="item.value == scope.row.version">{{item.label}}</span>
					</template>
				</el-table-column>
				<el-table-column label="所属实验" align='center'>
					<template slot-scope="scope">
						{{modeFloow.name}}
					</template>
				</el-table-column>
				<el-table-column prop="majorId" label="操作" width='200' align='center'>
					<template slot-scope="scope">
						<el-button type='primary' size='small' @click="openEditMode(scope.row)">编辑</el-button>
						<el-button type="danger" size='small' @click="openDeleteMode(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="resourceshow = false">关闭</el-button>
			</div>
			<el-dialog title="模式管理" width="600px" :close-on-press-escape='false' :close-on-click-modal='false' :append-to-body='true' :visible.sync="resourceChange" class='workDialog'>
				<el-form :model="modeDtoForm" :rules="rules" ref="modeDtoForm" label-width="100px">
					<el-form-item prop="version" :label-width="formLabelWidth" label="实验版本">
						<el-select v-model="modeDtoForm.version" placeholder="请选择实验版本" :disabled="isLock || !!modeDtoForm.vrResourceId" style="width: 100%;">
							<el-option v-for="item in versions" :key="item.value" :label="item.label" :value="item.value"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="mode" :label-width="formLabelWidth" label="实验模式">
						<el-select v-model="modeDtoForm.mode" placeholder="请选择" :disabled="isLock" style="width: 100%;">
							<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"> </el-option>
						</el-select>
					</el-form-item>
					<el-form-item label="实验地址" :label-width="formLabelWidth" prop="url">
						<el-col :span="24">
							<el-input v-model="modeDtoForm.url" autocomplete="off" placeholder="请输入实验地址" style="width: 100%;"></el-input>
						</el-col>
					</el-form-item>
					<!--<el-form-item prop="url" label="实验资源">
						<div class="drop-area el-upload-dragger" @click="clickElement($event, 'upload_folder')" @drop="handleFileDrop($event)" @dragleave="stopEvent($event)" @dragenter="stopEvent($event)" @dragover="stopEvent($event)">
							<i class="el-icon-upload"></i>
							<div class="el-upload__text">
								请将资源文件目录拖拽到此处
								<br />
								<em v-if="allFileNum > 0 && allFileNum === upFileNum">已上传</em>
								<em v-if="allFileNum > 0 && allFileNum > upFileNum">正在上传：{{upFileNum}}/{{allFileNum}}</em>
								<em v-if="!modeDtoForm.vrResourceId && allFileNum==0" style="color: #F56C6C;">未上传, 请选择目录</em>
								<div v-if="!allFileNum && !!modeDtoForm.vrResourceId" v-html="resourceMessage"></div>
								<input ref="upload_folder" webkitdirectory type="file" style="display: none" @change="handleFileInput($event)" />
							</div>
						</div>
						<ul v-if="objects && objects.length" class="el-upload-list el-upload-list--text" style="max-height: 130px;overflow: auto;">
							<li v-for="(object, index) in objects" :key="index" class="el-upload-list__item is-success">
								<a class="el-upload-list__item-name">
									<i class="el-icon-document"></i> {{ object.key }}
								</a>
								<label v-if="!object.uploading" class="el-upload-list__item-status-label"><i class="el-icon-upload-success el-icon-circle-check"></i></label>
								<div v-else role="progressbar" :aria-valuenow="object.progress" aria-valuemin="0" aria-valuemax="100" class="el-progress el-progress--line">
									<div class="el-progress-bar">
										<div class="el-progress-bar__outer" style="height: 2px;">
											<div class="el-progress-bar__inner" :style="`width: ${ object.progress || 0 }%;`"></div>
										</div>
									</div>
									<div class="el-progress__text" style="font-size: 12.8px;">{{ object.progress || 0 }}%</div>
								</div>
							</li>
						</ul>
					</el-form-item>-->
				</el-form>
				<div slot="footer" class="dialog-footer">
					<el-button @click="closeMode">取消</el-button>
					<el-button type="primary" @click="beforeSubmit">保存</el-button>
				</div>
			</el-dialog>
		</el-dialog>
	</div>
</template>

<script>
	import EditorMore from "@/components/Editor/index.vue";
	import { DateFormat } from '@/utils/date.js'
	import { putProgress, createMultipartUpload, listObjects } from "@/utils/oss.js";
	import { majorList } from '@/api/major.js'
	import { resourceSave, resourceUpdate, resourceRemove, vrResourceList } from '@/api/vrResource.js'
	import { detailExamineState, resourceDetailInsert, resourceDetailUpdate, resourceDetailDelete, resourceDetailPage, resourceDetailInfo } from '@/api/resource.js'
	export default {
		name: 'course',
		components: {
			EditorMore
		},
		data() {
			var checkNumber = (rule, value, callback) => {
				if(!value) {
					return callback(new Error('请填写数字'));
				} else if(isNaN(Number(value))) {
					return callback(new Error('请填写数字'));
				} else if(!Number.isInteger(Number(value))) {
					return callback(new Error('请输入整数'));
				} else {
					return callback();
				}
			};
			return {
				userinfo: '',
				name: '',
				mode: '',
				majorId: '',
				current: 1,
				limit: 10,
				total: 0,
				treeData: [],
				options: [{
					value: 1,
					label: '学习模式'
				}, {
					value: 2,
					label: '考核模式'
				}],
				versions: [{
					value: "WEBGL",
					label: 'webGL版本'
				}, {
					value: "THREEJS",
					label: 'three.js版本'
				}],
				dataloading: false,
				loadingData: false,
				majors: [],
				addStatus: false,
				editStatus: false,
				props: {
					value: 'id',
					label: 'name',
				},
				formLabelWidth: '110px',
				form: {
					name: '',
					majorId: '',
					cover: '',
					passScore: '',
					timeLimit: '',
					describes: '',
					introduction: '',
				},
				formEdit: {
					vrResourceDetailId: '',
					name: '',
					majorId: '',
					cover: '',
					passScore: '',
					timeLimit: '',
					describes: '',
					introduction: '',
				},
				rules: {
					name: [{
						required: true,
						message: '请输入实验名称'
					}],
					majorId: [{
						required: true,
						message: '请选择实验分类'
					}],
					introduction: [{
						required: true,
						message: '请输入实验介绍'
					}],
					describes: [{
						required: true,
						message: '请输入实验描述'
					}],
					passScore: [{
						validator: checkNumber
					}, {
						required: true,
						message: '请输入及格分'
					}],
					timeLimit: [{
						validator: checkNumber
					}, {
						required: true,
						message: '请输入限时'
					}],
					cover: [{
						required: true,
						message: '请上传实验封面'
					}],
					version: [{
						required: true,
						message: "请选择实验版本",
						trigger: "blur"
					}],
					url: [{
						required: true,
						message: "请输入实验地址",
						trigger: "blue"
					}],
					mode: [{
						required: true,
						message: "请选择实验模式",
						trigger: "change"
					}],
				},

				//批量管理
				tableshow: false,
				searchName: '',
				searchType: '',
				searchMode: '',
				taskList: [],
				examCurrent: 1,
				examLimit: 10,
				examTotal: 0,
				selections: [],

				//模式管理
				resourceshow: false,
				modeDtoList: [],
				modeFloow: {},
				resourceChange: false,
				modeDtoForm: {
					vrResourceDetailId: "",
					mode: "",
					version: "",
					attachPrefix: "",
					url: "",
				},
				isLock: false, // `isLock: true` 后可以上传文件, 禁止上传后修改路径
				objects: [],
				videoFlag: false,
				videoProgress: 0,
				allFileNum: 0,
				upFileNum: 0,
				resourceMessage: "", // 资源上传框提示信息
			}
		},
		created() {
			this.getMajorList();
			this.getList();
		},
		mounted() {

		},
		methods: {
			gettaskList() {
				var data = {
					mode: this.searchMode,
					name: this.searchName ? this.searchName : null,
					majorId: this.searchType ? this.searchType : null,
					pageNum: this.examCurrent,
					pageSize: this.examLimit,
				}
				resourceDetailPage(data).then(async res => {
					this.taskList = res.data.list;
					this.examTotal = res.data.total;
				})
			},
			addSelection(type) {
				var selections = this.selections;
				var vrDetails = [];
				if(selections && selections.length > 0) {
					selections.map(item => {
						vrDetails.push(item.vrResourceDetailId)
					})
					vrDetails = vrDetails.join(',');
					var data = {
						vrDetails,
						onOff: type
					}
					detailExamineState(data).then(res => {
						if(res.code == "200") {
							this.$message({
								type: 'success',
								message: res.msg
							})
							this.calcelSelection();
							this.currentChange(1);
						} else {
							this.$message({
								type: 'error',
								message: res.msg
							})
						}
					})
				} else {
					this.$message({
						type: 'error',
						message: '请先选择实验！'
					})
				}
			},
			handleExamChange(current) {
				this.examCurrent = current;
				this.gettaskList();
			},
			regettaskList() {
				this.examCurrent = 1;
				this.selections = [];
				this.taskList = [];
				this.gettaskList();
				this.tableshow = true;
			},
			selectionChange(val) {
				this.selections = val;
			},
			calcelSelection() {
				this.selections = [];
				this.tableshow = false;
				this.$refs.taskList.clearSelection()
			},
			getMajorList() {
				majorList({}).then(res => {
					this.majors = res.data || []
				})
			},
			getList() {
				var data = {
					mode: this.mode,
					name: this.name ? this.name : null,
					majorId: this.majorId,
					pageNum: this.current,
					pageSize: this.limit,
				}
				resourceDetailPage(data).then(res => {
					this.treeData = res.data.list;
					this.total = res.data.total;
				})
			},
			get_suffix(filename) {
				let pos = filename.lastIndexOf('.')
				let suffix = ''
				if(pos != -1) {
					suffix = filename.substring(pos)
				}
				return suffix
			},
			formRequest(file) {
				const uploadfile = file.file;
				const key = `szhjxpt/vrResourceDetailCover/${uploadfile.name}`;
				putProgress(key, uploadfile).then(res => {
					let e = {
						code: "200",
						success: true,
						message: '',
						data: key
					}
					file.onSuccess(e)
				});
			},
			formBannerSuccess(res, file, fileList) {
				if(res.code == "200") {
					this.form.coverFiles = [file];
					this.form.cover = res.data;
				}
			},
			formBannerRemove() {
				this.form.cover = '';
			},
			formEditBannerSuccess(res, file, fileList) {
				if(res.code == "200") {
					this.formEdit.coverFiles = [file];
					this.formEdit.cover = res.data;
				}
			},
			formEditBannerRemove() {
				this.formEdit.cover = '';
			},
			currentChange(current) {
				this.current = current;
				this.getList();
			},
			openAdd() {
				this.addStatus = true;
				try {
					this.$refs.addForm.clearValidate();
					this.$refs.addForm.resetFields();
				} catch(err) {}
			},
			introductionAddChange(data) {
				this.form.introduction = data.html;
			},
			add() {
				this.dataloading = true;
				setTimeout(_ => {
					this.dataloading = false;
				}, 1000)
				this.$refs.addForm.validate((valid) => { //添加
					if(valid) {
						var data = Object.assign({}, this.form);
						resourceDetailInsert(data).then(async res => {
							if(res.code == "200") {
								this.$notify({
									title: '提示',
									message: '添加成功',
									type: 'success'
								});
								this.closeAdd()
								this.getList();
							} else {
								this.$message({
									message: res.message,
									type: 'error'
								});
							}
						})
					}
				})
			},
			closeAdd() {
				this.form.coverFiles = [];
				this.form.majorId = '';
				this.$refs.addForm.clearValidate();
				this.$refs.addForm.resetFields();
				this.addStatus = false;
			},
			openEdit(item) {
				resourceDetailInfo({
					vrResourceDetailId: item.vrResourceDetailId
				}).then(res => {
					var data = Object.assign({}, item, res.data);
					data.coverFiles = [{
						name: item.name + '-封面',
						url: this.baseurl + item.cover
					}];
					data.vrExamineState = item.vrExamineState == 1 ? 1 : 0;
					this.formEdit = data;
					this.editStatus = true;
				})
			},
			introductionEditChange(data) {
				this.formEdit.introduction = data.html
			},
			edit() {
				this.dataloading = true;
				setTimeout(_ => {
					this.dataloading = false;
				}, 1000)
				this.$refs.editForm.validate((valid) => {
					if(valid) {
						var data = Object.assign({}, this.formEdit);
						resourceDetailUpdate(data).then(async res => {
							if(res.code == "200") {
								this.$notify({
									title: '提示',
									message: '更新成功',
									type: 'success'
								});
								this.closeEdit();
								this.getList();
							} else {
								this.$message({
									message: res.message,
									type: 'error'
								});
							}
						})
					}
				})
			},
			closeEdit() {
				this.formEdit.coverFiles = [];
				this.formEdit.majorId = '';
				this.$refs.editForm.clearValidate();
				this.$refs.editForm.resetFields();
				this.editStatus = false;
			},
			openDelete(item) {
				if(item.modeDtoList && item.modeDtoList.length > 0) {
					this.$notify({
						title: '提示',
						type: 'error',
						message: '当前实验下有资源，请删除关联实验资源后再进行此操作！'
					});
					return
				} else {
					this.$confirm('此操作将永久删除' + '【' + item.name + '】' + ', 是否继续?', '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					}).then(() => {
						resourceDetailDelete({
							vrResourceDetailId: item.vrResourceDetailId
						}).then(async res => {
							if(res.code == "200") {
								this.$notify({
									title: '提示',
									type: 'success',
									message: '删除成功!'
								});
								this.getList();
							}
						})
					}).catch(() => {
						this.$notify({
							title: '提示',
							type: 'info',
							message: '已取消删除'
						});
					});
				}
			},
			toJurisdiction() {
				this.$router.replace({
					name: 'vrResourceDetailsjurisdiction',
				});
			},
			openDetail(item) {
				this.$router.replace({
					name: 'vrResourceDetailInfo',
					query: {
						vrResourceDetailId: item.vrResourceDetailId
					}
				});
			},
			openInfo(item) {
				this.$router.replace({
					name: 'vrResourceInfo',
					query: {
						vrResourceDetailId: item.vrResourceDetailId
					}
				});
			},
			openResource(item) {
				this.modeFloow = item;
				this.getModeList();
				this.resourceshow = true;
			},
			getModeList() {
				vrResourceList({
					vrResourceDetailId: this.modeFloow.vrResourceDetailId
				}).then(res => {
					this.modeDtoList = res.data || [];
				})
			},
			openAddMode() {
				this.resourceChange = true;
				this.isLock = false;
				this.objects = [];
			},
			openEditMode(item) {
				this.modeDtoForm = Object.assign({}, this.modeDtoForm, item)
				this.resourceChange = true;
				this.isLock = false;
				//				this.checkOSSResource();
			},
			openDeleteMode(item) {
				this.$confirm('此操作将永久删除此资源， 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					resourceRemove({
						vrResourceId: item.vrResourceId
					}).then(async res => {
						if(res.code == "200") {
							this.$notify({
								title: '提示',
								type: 'success',
								message: '删除成功!'
							});
							this.getModeList();
							this.getList();
						}
					})
				}).catch(() => {
					this.$notify({
						title: '提示',
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			checkSuccess() {
				this.allFileNum = this.objects.length;
				this.upFileNum = this.objects.filter(item => item.uploading === false).length;
				if(this.allFileNum == this.upFileNum) {
					this.$refs["upload_folder"].value = ''
				}
			},
			handleResourceUpload(file, relativePath) {
				let majorId = this.modeFloow.majorId;
				let version = this.modeDtoForm.version;
				let mode = this.modeDtoForm.mode;
				const key = `szhjxpt/${majorId}/${mode}/${version}/${relativePath}`;
				// 检查重复上传
				let index = this.objects.findIndex(item => item.key === key);
				if(index > -1) {
					this.objects[index].file = file;
					return;
				}
				// 上传
				this.objects.push({
					key: key,
					file: file,
					uploading: true
				});
				createMultipartUpload(key, file, this.multiUploadProgress).then(({
					name,
					res
				}) => {
					const target = this.objects.find(object => object.key === key);
					target.uploading = false;
					// 更新lock状态
					this.checkSuccess()
					if(this.upFileNum === this.allFileNum) {
						this.$set(this, 'isLock', false)
					}
					// 通过任一 url 截取资源文件父目录, 通过 json 文件地址截取资源名称
					// url: http://zf-vr.oss-cn-hangzhou.aliyuncs.com/szhjxpt/6/1/WEBGL/MRWebGl/Build/MRWebGl.json
					// threejsurl: http://zf-vr.oss-cn-hangzhou.aliyuncs.com/szhjxpt/6/1/THREEJS/MRWebGl/index.html
					const durl = /https?:\/\/[\w.\-_%]*\/[\w.\-_%]*\/[\w.\-_%]*\/[\w.\-_%]*\/[\w.\-_%]*\/[\w.\-_%]*\//i;
					var jurl;
					if(version == WEBGL) {
						jurl = /[\w.:\-_\/%]*\/Build\/[\w.\-_%]*.json/i;
					} else {
						jurl = /[\w.:\-_\/%]*\/[\w.\-_%]*.html/i;
					}
					if(res && res.requestUrls) {
						//只保留vrAdmin到Build这一段
						var allUrl = res.requestUrls[0].match(durl)[0];
						this.modeDtoForm.url = 'szhjxpt' + allUrl.split('szhjxpt')[1];
						if(name && name.match(jurl)) {
							const node = res.requestUrls[0].split("/");
							if(version == WEBGL) {
								this.modeDtoForm.attachPrefix = node[node.length - 1].replace(".json", "")
							} else {
								this.modeDtoForm.attachPrefix = node[node.length - 1].replace(".html", "")
							}
						}
					}
				})
			},
			multiUploadProgress(progress, checkpoint) {
				if(!checkpoint) {
					return;
				}
				const target = this.objects.find(item => item.key === checkpoint.name);
				this.$set(target, "checkpoint", checkpoint);
				this.$set(target, "progress", Math.round(progress * 100));
			},
			handleFileInput(event) {
				const that = this
				this.checkField().then(() => {
					// 校验通过, 上传, 禁止修改
					this.isLock = true
					for(const file of event.target.files) {
						that.handleResourceUpload(file, file.webkitRelativePath || file.name)
					}
				}).catch(() => {
					// 不通过, 清空上传
					this.$refs["upload_folder"].value = ''
				})
			},
			handleFileDrop(event) {
				this.stopEvent(event);
				this.checkField()
					.then(() => {
						this.isLock = true;
						const items = event.dataTransfer.items;
						if(!items.length || items[0].kind !== "file") return;
						for(const item of items) {
							const entry = item.webkitGetAsEntry();
							this.loadChildFiles(entry, entry.name);
						}
					})
					.catch(() => {
						this.$refs["upload_folder"].value = "";
					});
			},
			loadChildFiles(entry, relativePath) {
				const that = this;
				if(entry.isFile) {
					entry.file(file => that.handleResourceUpload(file, relativePath));
					return;
				}
				const reader = entry.createReader();
				reader.readEntries(entries =>
					entries.forEach(entry =>
						that.loadChildFiles(
							entry,
							`${relativePath ? relativePath : ""}/${entry.name}`
						)
					)
				);
			},
			async checkOSSResource() {
				// 验证 OSS 文件目录存在
				const {
					res
				} = await listObjects(this.modeDtoForm.url)
				this.resourceMessage = res.requestUrls && res.requestUrls.length ?
					`<em style="color: #67C23A">资源已上传到服务器</em>` :
					`<em style="color: #F56C6C">资源已被删除, 需重新上传</em>`
			},
			beforeSubmit() {
				this.$refs.modeDtoForm.validate(valid => {
					if(valid) {
						var data = Object.assign({}, this.modeDtoForm, {
							vrResourceDetailId: this.modeFloow.vrResourceDetailId
						})
						if(this.modeDtoForm.vrResourceId) {
							resourceUpdate(data).then(res => {
								if(res.code == '200') {
									this.getModeList();
									this.getList();
									this.closeMode();
								} else {
									this.$message.error(res.message);
								}
							})
						} else {
							resourceSave(data).then(res => {
								if(res.code == '200') {
									this.getModeList();
									this.getList();
									this.closeMode();
								} else {
									this.$message.error(res.message);
								}
							})
						}
					}
				});
			},
			checkField() {
				const that = this;
				const filed = ["version", "mode"];
				return new Promise((resolve, reject) => {
					let success = true;
					that.$refs.modeDtoForm.validateField(filed, error => {
						if(error) {
							success = false;
						}
					});
					if(success) {
						resolve();
					} else {
						this.$message.error("请检查上传必要参数");
					}
				});
			},
			resetForm() {
				this.$refs.modeDtoForm.resetFields();
			},
			stopEvent(event) {
				event.stopPropagation();
				event.preventDefault();
			},
			clickElement(event, el) {
				event.stopPropagation();
				this.$refs[el].click();
			},

			closeMode() {
				this.modeDtoForm = {
					vrResourceDetailId: "",
					mode: "",
					version: "",
					attachPrefix: "",
					url: "",
				}
				this.isLock = false;
				this.objects = [];
				this.videoFlag = false;
				this.videoProgress = 0;
				this.allFileNum = 0;
				this.upFileNum = 0;
				this.resourceMessage = '';
				this.$nextTick(() => {
					this.$refs.modeDtoForm.clearValidate();
					this.resourceChange = false

				})
			},
		}
	}
</script>
<style type="text/css" scoped="scoped">
	.main-wrapper {
		margin: 0.75rem;
	}
	
	.content-filterbox {
		height: auto;
		width: 100%;
		box-sizing: border-box;
		padding: 0 15px;
		border-radius: 5px;
		border: 1px solid #cccccc;
		margin: 0 0 15px 0;
	}
	
	.content-filter {
		height: auto;
		width: 100%;
		box-sizing: border-box;
		padding: 15px 0 0 60px;
		border-bottom: 1px solid #cccccc;
		position: relative;
		min-height: 60px;
	}
	
	.content-filter:last-child {
		border-bottom: none;
		margin: 0;
	}
	
	.content-filtername {
		height: 60px;
		line-height: 60px;
		font-size: 16px;
		font-weight: 500;
		position: absolute;
		left: 0;
		top: 0;
	}
	
	.content-filteritem {
		height: 30px;
		line-height: 30px;
		font-size: 14px;
		padding: 0 15px;
		color: #666666;
		margin: 0 15px 15px 0;
		display: inline-block;
		cursor: pointer;
		border-radius: 5px;
	}
	
	.content-filteritem.active {
		color: #ffffff;
		background: #31bc7a;
	}
	
	.search-wrapper {
		margin-bottom: 0.5rem;
	}
	/* 表单 */
	
	.cover-content {
		height: 120px;
		width: 120px;
	}
	
	.el-icon-picture-outline {
		height: 50px;
		width: 50px;
		font-size: 30px;
		text-align: center;
		line-height: 50px;
		color: #909399;
		background-color: #f5f7fa;
	}
	/* 弹出框 */
	
	.changeStyle .el-dialog__header {
		background-color: #eef1f6;
	}
	
	.changeStyle .el-dialog__title {
		color: #0b87fb;
	}
	
	.changeStyle .dialog-content {
		height: calc(100vh - 180px);
		overflow: auto;
	}
</style>